package com.kehongborui.spring.service;

import com.kehongborui.spring.dao.UserMapper;
import com.kehongborui.spring.entity.User;
import com.kehongborui.spring.model.UserModel;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.kehongborui.spring.util.CommonUtil.isEmpty;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-08-01
 */
@Service
public class LoginService {
    // 自动注入 sqlSessionFactory
//    @Autowired
//    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    UserMapper userMapper;

    /**
     * 用户登录逻辑处理
//     * @param model
     * @return
     */
    public UserModel login(String username, String password) {
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        return userModel;
    }
    public UserModel login(UserModel model) {
        if (isEmpty(model.getPassword()) || isEmpty(model.getUsername())) {
            throw new RuntimeException("用户名或者密码不能为空");
        }

        // 获取SqlSession
//        SqlSession session = sqlSessionFactory.openSession();
//        UserMapper mapper = session.getMapper(UserMapper.class);

        // 查找用户
        User user = new User();
        BeanUtils.copyProperties(model, user);
        User retUser = userMapper.findByUsername(model.getUsername());
//        session.close();  // 关闭session

        if (retUser != null && retUser.getPassword().equals(model.getPassword())) {
            // 将 entity retUser 中的数据
            BeanUtils.copyProperties(retUser, model);
            return model;
        }

        return null;
    }
}
